/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/second-minimum-node-in-a-binary-tree
   @Language: C++
   @Datetime: 19-05-14 13:31
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	void dfs(TreeNode *root, int minval, int &second){
		if(root->val>second) return;
		if(root->val>minval) second=min(second,root->val);
		if(root->left) dfs(root->left,minval,second);
		if(root->right) dfs(root->right,minval,second);
	}
public:
	/**
	 * @param root: the root
	 * @return: the second minimum value in the set made of all the nodes' value in the whole tree
	 */
	int findSecondMinimumValue(TreeNode * root) {
		// Write your code here
		int second=INT_MAX;
		if(root) dfs(root,root->val,second);
		return second==INT_MAX?-1:second;
	}
};
